package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.apis.user.IUserClient;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleFreeMarkerService;
import com.heima.article.service.ApArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.article.dtos.ArticleInfoDto;
import com.heima.model.article.mess.ArticleVisitStreamMess;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author An
 */
@Slf4j
@Service
@Transactional
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    // 单页最大加载的数字
    private final static short MAX_PAGE_SIZE = 50;

    @Autowired
    private ApArticleMapper mapper;

    @Autowired
    private ApArticleConfigMapper apArticleConfigMapper;

    @Autowired
    private ApArticleContentMapper apArticleContentMapper;

    @Autowired
    private ApArticleFreeMarkerService apArticleFreeMarkerService;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private IUserClient iUserClient;


    /**
     * 根据参数加载文章列表
     *
     * @param loadType 1为加载更多  2为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Byte loadType, ArticleHomeDto dto) {
        // 检验页面传递的参数
        Integer size = dto.getSize();
        if (dto.getSize() == null || dto.getSize() == 0) {
            size = 10;
        }
        // 取较小值
        int minSize = Math.min(size, MAX_PAGE_SIZE);
        // 将较小值设置到dto中
        dto.setSize(minSize);

        // 文章频道校验
        if (StringUtils.isEmpty(dto.getTag())) {
            // 如果频道为空则查询所有
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }

        //时间校验
        if (dto.getMaxBehotTime() == null) dto.setMaxBehotTime(new Date());
        if (dto.getMinBehotTime() == null) dto.setMinBehotTime(new Date());

        // 查询数据
        List<ApArticle> apArticles = mapper.loadArticleList(dto, loadType);

        //结果返回
        return ResponseResult.okResult(apArticles);
    }

    /**
     * 保存app端相关文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveArticle(ArticleDto dto) {
        // 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 属性拷贝
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto, apArticle);

        // 判断是新增还是修改,通过请求是否携带id判断
        if (dto.getId() == null) {
            // 新增
            // 保存文章
            save(apArticle);

            // 保存文章配置
            ApArticleConfig apArticleConfig = new ApArticleConfig(apArticle.getId());
            apArticleConfigMapper.insert(apArticleConfig);

            // 保存文章内容
            ApArticleContent content = new ApArticleContent();
            content.setContent(dto.getContent());
            content.setArticleId(apArticle.getId());
            apArticleContentMapper.insert(content);
        } else {
            // 修改
            // 修改文章
            updateById(apArticle);

            // 修改文章内容
            // 根据文章的id查询到文章的内容
            ApArticleContent articleContent = apArticleContentMapper
                    .selectOne(Wrappers
                            .<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, dto.getId())
                    );
            // 设置文章的内容
            articleContent.setContent(dto.getContent());
            // 更新
            apArticleContentMapper.updateById(articleContent);
        }

        // 异步调用文章静态页面生成
        apArticleFreeMarkerService.buildArticleStaticPageToMinIO(dto.getContent(), apArticle);

        // 返回文章的id
        return ResponseResult.okResult(apArticle.getId());
    }

    /**
     * 加载文章用户行为
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        // 参数校验
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 获取当前登录用户
        ApUser user = ApUserThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 从redis中获取数据
        // 设置key
        String isLikeKey = BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId();
        String isUnlikeKey = BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId();
        String isCollectionKey = BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId();
        String isFollowKey = BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId();

        // 用户行为初始化
        Boolean islike = Boolean.FALSE;
        Boolean isunlike = Boolean.FALSE;
        Boolean iscollection = Boolean.FALSE;
        Boolean isfollow = Boolean.FALSE;

        // 从Redis中查询结果
        String likeResult = (String) cacheService.hGet(isLikeKey, user.getId().toString());
        if (StringUtils.isNotEmpty(likeResult)) {
            // 文章已被收藏
            islike = Boolean.TRUE;
        }

        String unlikeResult = (String) cacheService.hGet(isUnlikeKey, user.getId().toString());
        if (StringUtils.isNotEmpty(unlikeResult)) {
            // 不喜欢
            isunlike = Boolean.TRUE;
        }

        String isCollectionResult = (String) cacheService.hGet(isCollectionKey, user.getId().toString());
        if (StringUtils.isNotEmpty(isCollectionResult)) {
            // 文章已被收藏
            iscollection = Boolean.TRUE;
        }

        // 获取到当前用户关注列表里边的所有的作者
        Set<String> isFollowResult = cacheService.zRange(isFollowKey, 0, -1);
        // 如果数据已经同步到了数据库,则需要从数据库中查询
        ResponseResult result = iUserClient.queryFollow(dto.getAuthorId(), user.getId());

        // 判断当前登录用户的关注列表里面有没有该文章作者
        if (isFollowResult.contains(dto.getAuthorId().toString())) {
            // 关注了文章作者
            isfollow = Boolean.TRUE;
        } else if (result.getCode() == 200) {
            // 关注了作者
            isfollow = Boolean.TRUE;
        }

        // 封装查询结果
        HashMap<String, Boolean> resultMap = new HashMap<>();
        resultMap.put("islike", islike);
        resultMap.put("isunlike", isunlike);
        resultMap.put("iscollection", iscollection);
        resultMap.put("isfollow", isfollow);

        // 结果返回
        return new ResponseResult(200, resultMap);
    }

    /**
     * 加载文章列表
     *
     * @param dto
     * @param type      1 加载更多   2 加载最新
     * @param firstPage true 是首页  false 不是首页
     * @return
     */
    @Override
    public ResponseResult loadArticleListV2(ArticleHomeDto dto, Byte type, boolean firstPage) {
        if (firstPage) {
            //从缓存中获取数据
            String articleListStr = cacheService.get(ArticleConstants.HOT_ARTICLE_FIRST_PAGE + dto.getTag());
            if (StringUtils.isNotBlank(articleListStr)) {
                List<HotArticleVo> hotArticleVoList = JSON.parseArray(articleListStr, HotArticleVo.class);
                return ResponseResult.okResult(hotArticleVoList);
            }
        }
        return load(type, dto);
    }

    /**
     * 更新文章的分值  同时更新缓存中的热点文章数据
     *
     * @param mess
     */
    @Override
    public void updateScore(ArticleVisitStreamMess mess) {
        // 更新文章的点赞,评论,收藏,查看数量
        ApArticle article = updateArticleBehavior(mess);

        // 计算文章的得分
        Integer score = computeScore(article);
        score *= 3;  // 最终得分

        //3.替换当前文章对应频道的热点数据
        replaceDataToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + article.getChannelId());

        //4.替换推荐对应的热点数据
        replaceDataToRedis(article, score, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    /**
     * 替换热点文章
     *
     * @param article
     * @param score
     * @param key
     */
    private void replaceDataToRedis(ApArticle article, Integer score, String key) {
        String value = cacheService.get(key);
        if (StringUtils.isNotEmpty(value)) {
            List<HotArticleVo> voList = JSON.parseArray(value, HotArticleVo.class);

            // 判断一下当前要更新的文章是否再voList集合中
            Boolean flag = Boolean.FALSE;
            for (HotArticleVo vo : voList) {
                if (article.getId().equals(vo.getId())) {
                    vo.setScore(score);
                    flag = Boolean.TRUE;
                    break;
                }
            }

            // 如果当前更新的文章不在voList中,将文章添加到集合中,根据得分排序,截取前三十条
            if (!flag) {
                HotArticleVo vo = new HotArticleVo();
                BeanUtils.copyProperties(article, vo);
                vo.setScore(score);

                voList.add(vo);

                voList = voList.stream()
                        .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                        .limit(30)
                        .collect(Collectors.toList());
            }
            // 把voList集合写入到redis
            cacheService.set(key, JSON.toJSONString(voList));
        }
    }

    /**
     * 更新文章
     *
     * @param mess
     * @return
     */
    private ApArticle updateArticleBehavior(ArticleVisitStreamMess mess) {
        ApArticle apArticle = getById(mess.getArticleId());
        apArticle.setCollection((apArticle.getCollection() == null ? 0 : apArticle.getCollection()) + mess.getCollect());
        apArticle.setComment((apArticle.getComment() == null ? 0 : apArticle.getComment()) + mess.getComment());
        apArticle.setLikes((apArticle.getLikes() == null ? 0 : apArticle.getLikes()) + mess.getLike());
        apArticle.setViews((apArticle.getViews() == null ? 0 : apArticle.getViews()) + mess.getView());
        updateById(apArticle);
        return apArticle;
    }

    /**
     * 计算文章的具体分值
     *
     * @param apArticle
     * @return
     */
    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
